const express = require('express');
const router = express.Router();
const GoodModel = require('../models/goods');

router.get('/update/:author/:time/:title', function(req, res) {
	GoodModel.findOne({
		author: req.params.author,
		'time.day': req.params.time,
		title: req.params.title
	}).exec(function(err, data) {
		if(err) {
			res.json({
				error: 1,
				message: '出错'
			});
			var url = encodeURI('/u/' + req.params.author + '/' +
				req.params.time + '/' + req.params.title)
			return res.redirect(url);
		}
		if(!data) {
			res.json({
				error: 1,
				message: '数据不存在了哦'
			});
			return res.redirect('/');
		}

		res.render('title', {
			title: req.params.title,
			user: req.session.user,
			data,
		})
	})
})

router.get('/edit/:author/:time/:title', function(req, res) {

	GoodModel.findOne({
		author: req.params.author,
		'time.day': req.params.time,
		title: req.params.title
	}).exec(function(err, data) {
		if(err) {
			res.json({
				error: 1,
				message: '出错'
			});

			return res.redirect(url);
		}
		if(!data) {
			res.json({
				error: 1,
				message: '文件不存在'
			});
			return res.redirect('/');
		}
		res.render('edit', {
			title: '更新页面',
			user: req.session.user,
			data,
		})

	})

})
router.post('/edit/:author/:time/:title', function(req, res) {
	GoodModel.findOneAndUpdate({
		author: req.params.author,
		'time.day': req.params.time,
		title: req.params.title
	}, req.body).exec(function(err) {
		if(err) {
			res.json({
				error: 1,
				message: '出错'
			});
			return res.redirect('/edit');
		}
		return res.redirect('/');
	})
})
router.get('/edit/:author/:time/:title', function(req, res) {

	GoodModel.findOne({
		author: req.params.author,
		'time.day': req.params.time,
		title: req.params.title
	}).exec(function(err, data) {
		if(err) {
			res.json({
				error: 1,
				message: '出错'
			});

			return res.redirect('/');
		}
		if(!data) {
			res.json({
				error: 1,
				message: '文件不存在'
			});
			return res.redirect('/');
		}

		res.render('edit', {
			title: '更新页面',
			user: req.session.user,
			data,
		})

	})

})

router.get('/remove/:author/:time/:title', function(req, res) {
	GoodModel.findOneAndRemove({
		author: req.params.author,
		'time.day': req.params.time,
		title: req.params.title
	}).exec(function(err) {
		if(err) {
			res.json({
				error: 1,
				message: '出错'
			});
			// 生成固定的路径
			return res.redirect('/');
		}
		res.redirect('/')

	})
})

module.exports = router;